package com.njtoyo.taxi.admin.excel;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njtoyo.taxi.admin.mapper.master.entity.Driver;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverServiceLog;
import com.njtoyo.taxi.admin.mapper.master.entity.Taxi;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverServiceLogMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.TaxiMapper;
import com.njtoyo.taxi.admin.service.data.DriverServiceLogService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@SpringBootTest
@ActiveProfiles(value = "prod")
public class 出车司机 {

    @Autowired
    private DriverServiceLogMapper driverServiceLogMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private TaxiMapper taxiMapper;


    @Test
    public void driver() {
        ExcelWriter writer = ExcelUtil.getWriter("/Users/saber/Desktop/upload/driver.xls");
        List<Map<String, Object>> rows = new ArrayList<>();
        for (int i = 3; i > 0; i--) {
            Date selectDate = DateUtil.offsetDay(DateUtil.date(), -i);
            Date startDate = DateUtil.beginOfDay(selectDate);
            Date endDate = DateUtil.endOfDay(selectDate);
            List<DriverServiceLog> driverServiceLogs = driverServiceLogMapper.selectList(Wrappers.<DriverServiceLog>lambdaQuery()
                    .between(DriverServiceLog::getCreatedAt, startDate, endDate));
            Map<Long, List<DriverServiceLog>> collect = driverServiceLogs.stream().collect(Collectors.groupingBy(DriverServiceLog::getDriverId));
            for (Map.Entry<Long, List<DriverServiceLog>> entry : collect.entrySet()) {
                Long driverId = entry.getKey();
                Driver driver = driverMapper.selectById(driverId);
                Taxi taxi = taxiMapper.selectById(driver.getTaxiId());
                List<DriverServiceLog> driverServiceLogList = entry.getValue();
                //出车时长
                Integer sum = driverServiceLogList.stream().map(DriverServiceLog::getDuration).reduce(Integer::sum).orElse(0);
                Map<String, Object> row1 = new LinkedHashMap<>();
                row1.put("司机ID", driverId);
                row1.put("车牌号", taxi.getPlateNumber());
                row1.put("司机名称", driver.getName());
                row1.put("出车时长(秒)", sum);
                row1.put("日期", DateUtil.format(selectDate, "yyyy-MM-dd"));
                rows.add(row1);
            }
        }
        writer.write(rows, true);
        writer.close();

    }
}
